

<template>
  <div>
    <div>
      <el-table
          border
          ref="multipleTableRef"
          :data="tableData"
          style="width: 100%"
          default-expand-all
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection"  width="55" />
        <el-table-column label="专家组名称">
          <template #default="scope">{{ scope.row.name }}</template>
        </el-table-column>
        <el-table-column  label="专家人数" >
          <template #default="scope" >
            <div style="cursor: pointer;color: #2A91FE" @click="openpeopledetails(scope.row)">{{ scope.row.count }}</div>
          </template>
        </el-table-column>
        <el-table-column property="note" label="备注" />
        <el-table-column fixed="right" label="操作" min-width="120">
          <template #default="scope">
            <el-button link type="primary" size="small" @click="redact(scope.row)">
              编辑
            </el-button>
            <el-button link type="primary" size="small"  @click="openpeople(scope.row)">维护成员</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="example-pagination-block">
      <el-pagination
          layout="->,prev, pager, next, total"
          :total="count"
          currentPage1="10"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
  </div>

  <!--  编辑-->
  <el-dialog v-model="dialogFormVisible" title="编辑" width="50%">
    <div style="width: 90%">
      <el-form
          ref="ruleFormRef"
          :model="ruleForm"
          :rules="rules"
          label-width="100px"
          class="demo-ruleForm"
          :size="formSize"
          status-icon
      >
        <el-form-item label="专家组名称" prop="name">
          <el-input v-model="ruleForm.name" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input type="textarea" v-model="ruleForm.note" />
        </el-form-item>
        <el-form-item>
          <div style="margin: auto" >
          <el-button type="primary" @click="submitForm(ruleFormRef)">
            保存
          </el-button>
          </div>
          <!--          <el-button @click="resetForm(ruleFormRef)">重置</el-button>-->
        </el-form-item>
      </el-form>
    </div>

  </el-dialog>
  <!--  编辑-->
  <!--维护成员-->
  <el-dialog v-model="openpeopleVisible" title="维护成员" width="70%">
    <el-form :model="form"
             ref="formRef"
             class="demo-ruleForm"
             :size="formSize"
             status-icon>
      <div class="dialog-flex">
        <div>
          <el-form-item  label-width="120px" label="工作单位" >
            <el-input v-model="form.workUnit"  placeholder="请输入工作单位"/>
          </el-form-item>
          <el-form-item  label-width="120px" label="姓名"  >
            <el-input v-model="form.name" placeholder="请输入姓名"/>
          </el-form-item>
          <el-form-item  label-width="120px" label="职称">
            <el-select  clearable @focus="getzhichengOptions" value-key="value" v-model="form.titleId" placeholder="请选择职称">
              <el-option
                  v-for="item in zhichengOptions"
                  :key="item.codeColumn"
                  :label="item.valueColumn"
                  :value="item.codeColumn"
              />
            </el-select>
          </el-form-item>
          <el-form-item  label-width="120px" label="一级学科" prop="subjectId">
            <el-select
                clearable
                v-model="form.subjectId"
                placeholder="请选择一级学科"
                @focus="getyijixuekeOptions"
            >
              <el-option
                  v-for="item in yijixuekeOptions"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
              />
            </el-select>
          </el-form-item>
        </div>
        <div>
          <el-form-item  label-width="120px" label="最后学位" >
            <el-radio-group v-model="form.eduDegree" >
              <el-radio label="全部" value=""/>
              <el-radio label="博士" value="2"/>
              <el-radio label="硕士" value="3"/>
              <el-radio label="学士" value="4"/>
              <el-radio label="无" value="999"/>
            </el-radio-group>
          </el-form-item>
          <el-form-item  label-width="120px" label="性别">
            <el-radio-group v-model="form.sexId" >
              <el-radio label="全部" value=""/>
              <el-radio label="男" value="1"/>
              <el-radio label="女" value="0"/>
            </el-radio-group>
          </el-form-item>
          <el-form-item  label-width="120px" label="研究方向"  >
            <el-input v-model="form.researchField" type="textarea" />
          </el-form-item>
        </div>
      </div>



      <el-form-item>
        <el-button style="margin:auto" type="primary" @click="onSubmit">查询</el-button>
      </el-form-item>
    </el-form>

    <div class="edit_fei">
      <el-transfer
          :titles="['可选专家', '已有专家']"
          v-model="value"
          :props="{ key: 'id',label: 'name'}"
          :data="data"
          style="margin-left: 50px"
      />

    </div>
    <div style="text-align: center">
      <el-button  type="primary"   @click="save()">保存</el-button>
      <el-button    @click="openpeopleVisible = false">关闭</el-button>
    </div>

  </el-dialog>

  <el-dialog v-model="openListpeopledetailsVisible" title="专家组成员查看" width="70%">
    <el-table :data="ListpeopledetailsData">
      <el-table-column  label="姓名" >
        <template #default="scope" >
          <div style="cursor: pointer;color: #2A91FE" @click="dialogopenpeopledetails(scope.row)">{{ scope.row.name }}</div>
        </template>
      </el-table-column>
      <el-table-column  label="性别" >
        <template #default="scope" >
          <div v-if=" scope.row.sexId ==1">男</div>
          <div v-if=" scope.row.sexId ==0">女</div>
        </template>
      </el-table-column>
      <el-table-column property="birthday" label="出生日期" />
      <!--      <el-table-column property="eduDegree" label="最后学位" />-->
      <el-table-column label="最后学位">
        <template #default="{ row }">
          {{ getEduDegreeName(row.eduDegree) }}
        </template>
      </el-table-column>
      <el-table-column label="最后学历">
        <template #default="{ row }">
          {{ getEduLevelName(row.eduLevel) }}
        </template>
      </el-table-column>
      <!--      <el-table-column property="eduLevel" label="最后学历" />-->
    </el-table>
  </el-dialog>
  <zjrcpeopleDetails :activ="activ"  :obj="obj"  @close-dialog="activ = false"></zjrcpeopleDetails>

</template>
<script lang="ts" setup>
import { DrawerProps, ElMessage, ElMessageBox } from "element-plus";
import {
  getExpertList,
  insertExpertGroup,
  selectExpertGroupList,
  deletExpertGroup,
  updateExpertGroup,
  insertExpertGroupPerson
} from "@/api/researcherNavApi/zjfzApi";
import { getCategory } from "@/api/researcherNavApi/researcherNavApi";
import { getExpertHaveList } from "@/api/researcherNavApi/zjrcApi";
import zjrcpeopleDetails from './../../../components/peopleDetails/zjrcpeopleDetails.vue';
import { onBeforeMount, ref, reactive } from "vue";

const getEduLevelName = (eduLevelId) => {
  if (eduLevelId === undefined || eduLevelId == null) {
    return '未知';
  }
  const eduLevelMap = {
    3: '大专',
    4: '中专',
    0: '博士研究生',
    1: '硕士研究生',
    2: '本科',
    5: '其他'
  };
  return eduLevelMap[eduLevelId] || '未知';
};

const getEduDegreeName = (eduDegreeId) => {
  if (eduDegreeId === undefined || eduDegreeId == null) {
    return '未知';
  }
  const eduDegreeMap = {
    2: '博士',
    3: '硕士',
    4: '学士',
    999: '无'
  };
  return eduDegreeMap[eduDegreeId] || '未知';
};

// 人名弹窗
///查看详情
const activ = ref(false);
const obj = ref('');
const dialogopenpeopledetails = function (row) {
  activ.value = true;
  console.log(activ.value);
  obj.value = row.id;
};

// 人数弹窗
const openListpeopledetailsVisible = ref(false);
const ListpeopledetailsData = ref([]);
const openpeopledetails = function (row) {
  getExpertHaveList({
    groupId: row.id
  })
      .then((res) => {
        if (res.code === 200) {
          openListpeopledetailsVisible.value = true;
          ListpeopledetailsData.value = res.data;
        }
      });
};

// 职称
const zhichengOptions = ref([]);
// 一级学科
const yijixuekeOptions = ref([]);
// 获取职称下拉
const getzhichengOptions = function () {
  getCategory(
      {
        'bizName': '职称单选'
      }
  )
      .then((res) => {
        zhichengOptions.value = res.data;
      });
};
const getyijixuekeOptions = function () {
  getCategory(
      {
        'bizName': '一级学科'
      }
  )
      .then((res) => {
        yijixuekeOptions.value = res.data;
      });
};

const openpeopleVisible = ref(false);
// 穿梭框
const data = ref([]);
const value = ref([]);
const rowid = ref('');
const peopleObj = ref([])
const openpeople = function (row: any) {
  openpeopleVisible.value = true;
  Object.keys(form).forEach(key => {
    form[key] = ''; // 将每个字段重置为空字符串或其他默认值
  });
  data.value = [];
  value.value = [];
  peopleObj.value =[]
  rowid.value = row.id;
  getExpertList(form)
      .then((res) => {
        console.log(res);
        data.value = res.data;
      });
  getExpertHaveList({
    groupId: rowid.value
  })
      .then((res) => {
        let rightA = [];
        for (let i = 0; i < res.data.length; i++) {
          rightA.push(res.data[i].id);
          peopleObj.value.push(res.data[i]);
        }
        console.log(value.value);
        console.log( peopleObj.value);
        value.value = rightA;
      });
};

const form = reactive({
  name: '', // 人名
  titleId: '',// 职称
  subjectId: '',// 一级学科
  eduDegree: '',// 最后学位
  sexId: '',// 性别
  workUnit: '',// 工作单位
  researchField: "",// 研究方向
});

const onSubmit = () => {
  getExpertList(form)
      .then((res) => {
        console.log(res);
        data.value = res.data;
        if (peopleObj.value && peopleObj.value.length > 0) {
          for (let i = 0; i < peopleObj.value.length; i++) {
            const currentPerson = peopleObj.value[i];
            // 检查 data.value 中是否已存在该元素
            const isExists = data.value.find((item) => item.id === currentPerson.id);
            if (!isExists) {
              data.value.push(currentPerson);
            }
          }
        }
      })
  // getExpertHaveList({
  //   groupId:rowid.value
  // })
  //     .then((res)=>{
  //       let rightA = []
  //       for (let i = 0; i < res.data.length; i++) {
  //         rightA.push(res.data[i].id)
  //       }
  //       value.value = rightA
  //     })
};

const save = () => {
  if (value.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '分组成员不能为空'
    });
  } else {
    insertExpertGroupPerson({
      expertIdList: value.value,
      groupId: rowid.value
    })
        .then((res) => {
          if (res.code === 200) {
            ElMessage({
              type: 'success',
              message: res.data,
            });
            openpeopleVisible.value = false;
            getlist(1, 10);
          }
        });
  }
};

const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
  console.log(val, 'console.log(handleSelectionChange)');
};

const tableData = ref([]);

// 删除
const open = () => {
  if (multipleSelection.value.length < 1) {
    ElMessage({
      type: 'warning',
      message: '请选择想要删除的分组',
    });
  } else {
    ElMessageBox.confirm(
        '确认！删除这条数据?',
        '提醒',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
    )
        .then(() => {
          let deleteArr = [];
          for (let i = 0; i < multipleSelection.value.length; i++) {
            deleteArr.push(multipleSelection.value[i].id);
          }
          deletExpertGroup({ 'idList': deleteArr })
              .then((res) => {
                if (res.code === 200) {
                  ElMessage({
                    type: 'success',
                    message: res.data,
                  });
                  getlist(1, 10);
                } else {
                  ElMessage({
                    type: 'info',
                    message: res.msg,
                  });
                }
              });
        })
        .catch(() => {
          // 用户取消删除，不做任何操作
        });
  }
};

// 编辑
const dialogFormVisible = ref(false);
const redact = function (row: any) {
  dialogFormVisible.value = true;
  Object.assign(ruleForm, {
    name: row.name, // 分组名
    note: row.note, // 备注
    id: row.id
  });
};

const formSize = ref('default');
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  name: '',
  note: '',
});

interface RuleForm {
  name: string
  note: string
}

const rules = reactive<FormRules<RuleForm>>({
  name: [
    { required: true, message: '请输入专辑组名称', trigger: 'blur' },
  ],
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      updateExpertGroup(ruleForm)
          .then((res) => {
            if (res.code === 200) {
              ElMessage({
                type: 'success',
                message: res.data,
              });
              dialogFormVisible.value = false;
              getlist(1, 10);
            } else {
              ElMessage({
                type: 'info',
                message: res.msg,
              });
            }
          });
    } else {
      console.log('error submit!', fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

// 编辑
const getlist = function (pages, pagesizes) {
  selectExpertGroupList({
    page: pages,
    pageSize: pagesizes
  })
      .then((res) => {
        console.log(res);
        tableData.value = res.data.list;
        count.value = res.data.count;
      });
};

// 分页
const count = ref(0);

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
};
const handleCurrentChange = (val: string) => {
  getlist(Number(val), 10);
  console.log(`current page: ${val}`);
};

onBeforeMount(() => {
  getlist(1, 10);
});

// 暴露删除
defineExpose({ open, getlist });
</script>

<style scoped lang="scss">
.flex-input {
  display: flex;
  margin: 10px 5px 10px 0;
}
.flex-input > div {
  margin-right: 10px;
  width: 20%;
}
.sss > div {
  margin: 5px 3px;
}
.dialog-flex {
  display: flex;
}
.dialog-flex > div {
  width: 50%;
}
.edit_fei {
  :deep(.el-transfer-panel) {
    width: 40% !important;
  }
}
</style>